<?php
class Taobao
{
    public $data = [];
    private $union;

    /**
     *
     * 已付款：指订单已付款，但还未确认收货
     * 已收货：指订单已确认收货，但商家佣金未支付
     * 已结算：指订单已确认收货，且商家佣金已支付成功
     * 已失效：指订单关闭/订单佣金小于0.01元，订单关闭主要有： * 1）买家超时未付款； * 2）买家付款前，买家/卖家取消了订单； * 3）订单付款后发起售中退款成功；
     * 3：订单结算，
     * 12：订单付款，
     * 13：订单失效，
     * 14：订单成功
    //0	默認 1	待支付 2	已支付 3	已退款 4	已完成 5	已失效 6	已結算 11	已取消
    //3：訂單結算， 12：訂單付款， 13：訂單失效， 14：訂單成功
     */
    public $status = [
        12 => 2,
        13 => 11,
        14 => 4,
        3 => 6,
    ];

    public function __construct($union)
    {
        $this->union = $union;
    }

    function createSign($paramArr)
    {
        $sign = $this->union['appSecret'];
        ksort($paramArr);
        foreach ($paramArr as $key => $val) {
            if ($key != '' && $val != '') {
                $sign .= $key . $val;
            }
        }
        $sign .= $this->union['appSecret'];
        $sign = strtoupper(md5($sign));
        return $sign;
    }

    /*
     拼参数方法
     */
    function createStrParam($paramArr)
    {
        $strParam = '';
        foreach ($paramArr as $key => $val) {
            if ($key != '' && $val != '') {
                $strParam .= $key . '=' . urlencode($val) . '&';
            }
        }
        return $strParam;
    }


    /**
     *
     * 订单处理
     */
    private function returnOrderDeal($data)
    {
        $responseTurnData = [];
        foreach ($data as $k => $v) {
            if (!isset($v['relation_id'])) {
                $v['rid'] = '0';
            }
            $order_status = $this->status[$v['tk_status']];
            $item_price = 0;
            if (isset($v['item_price'])) {
                $item_price = $v['item_price'];
            } else {
                if (isset($v['alipay_total_price'])) {
                    $item_price = $v['alipay_total_price'];
                }
            }
            $turnData = [
                'orderId' => $v['trade_id'],
                'orderStatus' => $order_status,
                'orderSrc' => "taobao",
                'tag' => "淘宝",
                'tagItem' => $v['order_type'],
                'name' => $v['item_title'],
                'goodsId' => isset($v['item_id']) ? $v['item_id'] : '',
                'images' => $v['item_img'],
                'rid' => isset($v['relation_id']) ? $v['relation_id'] : 0,
                'shopName' => $v['seller_nick'],
                'price' => $item_price,
                'orderType' => $v['refund_tag'] == 1 ? 2 : 1,
                'payMoney' => isset($v['alipay_total_price']) && !empty($v['alipay_total_price']) ? $v['alipay_total_price'] : 0,
                'rebateAmount' => doubleval($v['pub_share_fee']) > 0 ? $v['pub_share_fee'] : $v['pub_share_pre_fee'],
                'incomeRate' => $v['total_commission_rate'] ? $v['total_commission_rate'] : $v['income_rate'],
                'orderCreateTime' => $v['tk_create_time'],
                'orderPaidTime' => isset($v['tk_paid_time']) ? $v['tk_paid_time'] : null,
                'orderEarningTime' => isset($v['tk_earning_time']) ? $v['tk_earning_time'] : null,
                'settleTime' => isset($v['tk_earning_time']) ? $v['tk_earning_time'] : null,
            ];
            $responseTurnData[] = $turnData;
        }
        return $responseTurnData;
    }


    public function get_order($start_time, $end_time, $position_index = '', $page_no = 1, $up = 0,&$responseResult=[])
    {
        //参数数组
        $paramArr = array(
            'app_key' => $this->union['appKey'],
            'method' => 'taobao.tbk.order.details.get',
            'format' => 'json',
            'v' => '2.0',
            'sign_method' => 'md5',
            'timestamp' => date('Y-m-d H:i:s'),
            'fields'         => 'nick,type,user_id',
            // 'nick' => 'sandbox_c_1'
            'query_type'     => 1,
            'position_index' => $position_index,
            'page_size'      => 100,
            'start_time'     => '2022-03-06 16:00:00',//$start_time,
            'end_time'       => '2022-03-06 17:00:00',//$end_time,
            'jump_type'      => 1,
            'page_no'        => $page_no,
            'order_scene'    => 2
        );
        if ($up) {
            $paramArr['order_scene'] = 1;
        }

        //生成签名
        $sign = $this->createSign($paramArr);
        //组织参数
        $strParam = $this->createStrParam($paramArr);
        $strParam .= 'sign=' . $sign;
        //访问服务
        $url = 'http://gw.api.taobao.com/router/rest?' . $strParam;
        $result = file_get_contents($url);
        $result = json_decode($result, true);
        $res    = $result['tbk_order_details_get_response']['data'];
        if ($res['results'] == [] && $responseResult == []) {
            return [];
        }
        if ($res['results'] != []) {
            if ($responseResult == []) {
                $responseResult = $res['results']['publisher_order_dto'];
            } else {
                $responseResult = array_merge($responseResult, $res['results']['publisher_order_dto']);
            }
        }
        if ($res['has_next']) {
            $this->get_order($start_time, $end_time, $res['position_index'], $res['page_no'] + 1, $up,$responseResult);
        }
        return $this->returnOrderDeal($responseResult);
    }
    
    
    

    public function get_order_chufa($start)
    {
        $paramArr                  = $this->pub_params();
        $paramArr['method']        = 'taobao.tbk.dg.punish.order.get';
        $search_option             = [
            'span'      => 1,
            'page_no' => 1,
            'page_size' => 10000,
            'start_time'  => $start,

        ];
        $paramArr['af_order_option'] = json_encode($search_option);
        $sign                      = $this->createSign($paramArr);
        //组织参数
        $strParam = $this->createStrParam($paramArr);

        $strParam .= 'sign=' . $sign;
        //访问服务
        $url = 'https://eco.taobao.com/router/rest?' . $strParam;
        $result = json_decode(file_get_contents($url), true)['tbk_dg_punish_order_get_response']['result']['data']['results'];
        $count = 0;
        if (isset($result['result']) && !empty($result['result'])) {
            $count = count($result['result']);

            foreach ($result['result'] as $val){
                $orderDb = new Order();
                $where = "order_id = '{$val['tb_trade_id']}'";
                $info = $orderDb->findFirst($where);
                $info->order_chufa = 1;
                if($info){
                    if($val['punish_status'] == 1){
                        $info->order_status = 6;
                        $info->remark = '违规订单解冻!';
                    } else {
                        $info->remark = '违规订单冻结!';
                        $info->order_status = 5;
                    }
                    $f_order_commissions = new OrderCommissions();
                    $wheres['conditions'] = "order_id = '{$info->order_id}'";
                    $commission = $f_order_commissions->find($wheres);
                    if(!empty($commission->toarray())){
                        foreach ($commission as $vals){
                            if($val['punish_status'] == 1){
                                $vals->order_status = 6;
                            } else {
                                $vals->order_status = 5;
                            }
                            $vals->save();
                        }
                    }
                    $info->save();
                }
            }
        }
        return $count;
    }

    
    

    public function pub_params()
    {
        return array(
            'app_key' => $this->union['appKey'],
            'method' => '',
            'format' => 'json',
            'v' => '2.0',
            'sign_method' => 'md5',
            'timestamp' => date('Y-m-d H:i:s'));
    }

    public function get_order_last($start)
    {
        $paramArr                  = $this->pub_params();
        $paramArr['method']        = 'taobao.tbk.relation.refund';
        $search_option             = [
            'page_size'   => 1,
            'search_type' => 1,
            'refund_type' => 2,
            'start_time'  => $start,
            'page_no'     => 1,
            'biz_type'    => 1
        ];
        $paramArr['search_option'] = json_encode($search_option);
        $sign                      = $this->createSign($paramArr);

        //组织参数
        $strParam = $this->createStrParam($paramArr);
        $strParam .= 'sign=' . $sign;
        //访问服务
        $url = 'https://eco.taobao.com/router/rest?' . $strParam;
        $result = json_decode(file_get_contents($url), true)['tbk_relation_refund_response']['result'];
        return $result;
        var_dump($result);
        die;
    }


    /**
     * 生成淘口令
     */
    public function couponUrlToText($params)
    {
        require_once dirname(__DIR__) . "/plugins/taobaoClient/TopClient.php";
        require_once dirname(__DIR__) . "/plugins/taobaoClient/TbkTpwdCreateRequest.php";
        $topClient            = new \TopClient();
        $topClient->appkey    = $this->union['appKey'];
        $topClient->secretKey = $this->union['appSecret'];
        $req                  = new TbkTpwdCreateRequest();
        $req->setText($params['title']);
        $req->setUrl($params['url']);
        $req->setLogo($params['image']);
        //$req->setUserId($userrid);
        $res = $topClient->execute($req);
        if (isset($res->data)) {
            $model = str_replace("￥", "", $res->data->model);
            $model = "($model)";
            $password_simple=$res->data->password_simple;
            return ['code' => 1, 'data' => $model,'model'=>$password_simple];
        } else {
            return ['code' => 0, 'msg' => $res->sub_msg];
        }
    }


    /**
     * @param $sceneId 活动id
     * @adzoneid 用户授权id
     * 淘宝客-推广者-官方活动转链
     */
    public function activitylink($sceneId, $relationid)
    {
        require_once dirname(__DIR__) . "/plugins/taobaoClient/TopClient.php";
        require_once dirname(__DIR__) . "/plugins/taobaoClient/TbkActivitylinkGetRequest.php";
        $c            = new TopClient;
        $c->appkey    = $this->union['appKey'];
        $c->secretKey = $this->union['appSecret'];
        $req          = new TbkActivitylinkGetRequest;
        $req->setPlatform("2");
        $req->setAdzoneId($this->union['androidPid']);//108976400399
        $req->setPromotionSceneId($sceneId);
        //$req->setSubPid("mm_116147303_36832537_108976400399");//mm_116147303_36832537_108976400399
        $req->setRelationId($relationid);
        $resp = $c->execute($req);
        if (isset($resp->result_code) && $resp->result_code == 200) {
            return ['code' => true, 'data' => $resp->data];
        } else {
            return ['code' => false, 'data' => $resp->sub_msg];
        }
    }


    /**
     * 淘宝官方活动饿了么转链 ----新版
     */
    public function activitylink_new($activity_material_id, $relationid,$source="android")
    {
        require_once dirname(__DIR__) . "/plugins/taobaoClient/TopClient.php";
        require_once dirname(__DIR__) . "/plugins/taobaoClient/TbkActivityInfoGetRequest.php";
        $c            = new TopClient;
        $c->appkey    = $this->union['appKey'];
        $c->secretKey = $this->union['appSecret'];
        $req          = new TbkActivityInfoGetRequest;
        $req->setActivityMaterialId($activity_material_id);
        $req->setAdzoneId($this->union['androidMm']);
        //$req->setSubPid("mm_1_2_3");
        $req->setRelationId($relationid);
        $resp = $c->execute($req);
        if (isset($resp->data)) {
            $responseMsg['app_url'] = isset($resp->data->click_url) ? $resp->data->click_url : '';
            $responseMsg['url'] = isset($resp->data->click_url) ? $resp->data->click_url : '';
            $responseMsg['short_url'] = isset($resp->data->short_click_url) ? $resp->data->short_click_url : '';
            $responseMsg['page_path'] = isset($resp->data->wx_miniprogram_path) ? $resp->data->wx_miniprogram_path : '';
            $responseMsg['wx_code'] =  isset($resp->data->wx_qrcode_url) ? $resp->data->wx_qrcode_url : '';
            return ['status'=>true,'msg'=>'获取成功','data'=>$responseMsg];
        } else {
            return ['status' => false, 'msg' => $resp->sub_msg];
        }
    }


    public function get_order_time($start_time, $end_time, $position_index = '', $page_no = 1, $up = 0)
    {
        //参数数组
        $paramArr = array(
            'app_key' => $this->union['appKey'],
            'method' => 'taobao.tbk.order.details.get',
            'format' => 'json',
            'v' => '2.0',
            'sign_method' => 'md5',
            'timestamp' => date('Y-m-d H:i:s'),
            'fields'         => 'nick,type,user_id',
            // 'nick' => 'sandbox_c_1'
            'query_type'     => 1,
            'position_index' => $position_index,
            'page_size'      => 100,
            'start_time'     => $start_time,
            'end_time'       => $end_time,
            'jump_type'      => 1,
            'page_no'        => $page_no,
            'order_scene'    => 2
        );
        if ($up) {
            $paramArr['order_scene'] = 1;
        }
        //生成签名
        $sign = $this->createSign($paramArr);
        //组织参数
        $strParam = $this->createStrParam($paramArr);
        $strParam .= 'sign=' . $sign;
        //访问服务
        $url = 'http://gw.api.taobao.com/router/rest?' . $strParam;
        $result = file_get_contents($url);
        $result = json_decode($result, true);
        $res = $result['tbk_order_details_get_response']['data'];
        if ($res['results'] == [] && $this->data == []) {
            return [];
            //echo 111;die;
        }
        if ($res['results'] != []) {
            if ($this->data == []) {
                $this->data = $res['results']['publisher_order_dto'];
            } else {
                $this->data = array_merge($this->data, $res['results']['publisher_order_dto']);
            }
        }
        if ($res['has_next']) {
            $this->get_order($start_time, $end_time, $res['position_index'], $res['page_no'] + 1, $up);
        }
        return $this->data;

    }

    /**
     * 精选物料  母婴
     * @param $MaterialId
     * @param $page
     * @param int $size
     * @return mixed
     */
    public function TbkDgOptimusMaterialRequest($MaterialId, $page, $size = 10)
    {
        require_once dirname(__DIR__) . "/plugins/taobaoClient/TopClient.php";
        require_once dirname(__DIR__) . "/plugins/taobaoClient/TbkDgOptimusMaterialRequest.php";
        $c            = new TopClient;
        $c->appkey    = $this->union['appKey'];
        $c->secretKey = $this->union['appSecret'];
        $req          = new TbkDgOptimusMaterialRequest;
        $req->setPageSize($size);
        $req->setAdzoneId($this->union['androidMm']);
        $req->setPageNo($page);

        $req->setMaterialId($MaterialId);
        $resp = $c->execute($req);

        if (!empty($resp->result_list->map_data)) {

            $list = array();
            foreach ($resp->result_list->map_data as $val) {
                $list[] = (array)$val;
            }
            $list = $this->trun_list($list);
            return $list;
        } else {
            return array();
        }
    }


    public function optimus_material($start,$MaterialId='28017')
    {
        require_once dirname(__DIR__) . "/plugins/taobaoClient/TopClient.php";
        require_once dirname(__DIR__) . "/plugins/taobaoClient/TbkDgOptimusMaterialRequest.php";

        $topClient            = new TopClient();
        $topClient->appkey    = $this->union['appKey'];
        $topClient->secretKey = $this->union['appSecret'];
        $req                  = new TbkDgOptimusMaterialRequest();
        $req->setPageSize($start['page_size']);
        $req->setAdzoneId($this->union['androidMm']);
        $req->setPageNo($start['page']);
        $req->setMaterialId($MaterialId);   //6708 28017
        if(isset($start['imei']) && !empty($start['imei'])) {
            $req->setDeviceType($start['imei']);
            $req->setDeviceValue(md5($start['imei']));
            $req->setDeviceEncrypt("MD5");
            $req->setDeviceType("IMEI");
        }
        $res = $topClient->execute($req);
        $res = \Common\Common::transition_array($res);
        if($MaterialId == '34616'){
            return $res['result_list']['map_data'];
        }
        $result['data'] = [];
        $result['page'] = '';

        if(isset($res['result_list']) && $res['result_list']['map_data']){
            $result['data'] = $this->trun_list($res['result_list']['map_data']);
            if(count($res['result_list']['map_data']) >= 10){
                $result['min_id'] = $start['page']+1;
            }
        }

        return $result;
    }


    //精选物料公共列表转换
    public function trun_list($res)
    {
        $data = [];
        $site = "haodanku";
        foreach ($res as $k => $v) {
            $arr                  = [
                "GoodsId"     => $v['item_id'],
                "Title"       => $v['title'],
                "ShortTitle"  => $v['item_description'],
                "ShopType"    => "淘宝",
                "PicLogo"     => (strpos($v['pict_url'],'http') !== false) ? $v['pict_url'].'_310x310.jpg' : 'https:'.$v['pict_url'].'_310x310.jpg',
                "CouponMoney" => $v['coupon_amount'],
                "Price"       => $v['zk_final_price'],
                "EndPrice"    => sprintf("%.2f", $v['zk_final_price'] - $v['coupon_amount']),
                "MonthSale"   => $v['volume'],
                "Site"        => $site,
                'ShopName'    => $v['shop_title'],
                'IsAd'        => 0,
                'VideoUrl'     => '',
                'CouponTotal' => isset($v['coupon_total_count']) ? $v['coupon_total_count'] : '0',
            ];
            $arr["CouponSurplus"] = isset($v['coupon_remain_count']) ? $v['coupon_remain_count'] : 0;
            $arr["Commission"]    = sprintf("%.2f", $arr['EndPrice'] * ($v['commission_rate'] / 100));
            $data[]               = $arr;
        }
        return $data;
    }


    /*
     获取授权方法
     */
    public function get_token($params)
    {
        //参数数组
        $pub      = $paramArr = array(
            'app_key' => $this->union['appKey'],
            'method' => '',
            'format' => 'json',
            'v' => '2.0',
            'sign_method' => 'md5',
            'timestamp' => date('Y-m-d H:i:s'),
        );
        $paramArr = array_merge($paramArr, $params);
        //生成签名
        $sign = $this->createSign($paramArr);
        //组织参数
        $strParam = $this->createStrParam($paramArr);
        $strParam .= 'sign=' . $sign;
        //访问服务
        $url = 'https://eco.taobao.com/router/rest?' . $strParam;
        $result = file_get_contents($url);
        $result = json_decode($result, true);
        if(isset($result['error_response'])){
            return ['status'=>false,'msg'=>$result['error_response']['sub_msg']];
        }
        $token  = json_decode($result['top_auth_token_create_response']['token_result'], true)['access_token'];
        $tb_nickname = json_decode($result['top_auth_token_create_response']['token_result'], true)['taobao_user_nick'];
        $res['tb_nickname'] = urldecode($tb_nickname);
        $params = [
            'method'       => 'taobao.tbk.sc.publisher.info.save',
            'inviter_code' => $this->union['inviterCode'],//$this->getInviterCode(),
            'info_type'    => 1,
            'simplify'     => true,
            'relation_app' => 'common',
            'session'      => $token,
        ];
        $paramArr = array_merge($pub, $params);
        //生成签名
        $sign = $this->createSign($paramArr);
        //组织参数
        $strParam = $this->createStrParam($paramArr);
        $strParam .= 'sign=' . $sign;
        //访问服务
        $url = 'https://eco.taobao.com/router/rest?' . $strParam;
        $result = file_get_contents($url);
        $result = json_decode($result, true);
        if(isset($result['error_response'])){
            return ['status'=>false,'msg'=>$result['error_response']['sub_msg']];
        }
        $res['tb_rid'] = $result['tbk_sc_publisher_info_save_response']['data']['relation_id'];
        $ret = $this->publisher_info_save($token);
        if(!$ret['status']){
            return ['status'=>false,'msg'=>$ret['msg']];
        }
        $res['special_id'] = $ret['data'];
        return ['status'=>true,'msg'=>'获取成功','data'=>$res];
    }


    /*
    *绑定备案
    */
    public function publisher_info_save($sessionKey){
        require_once dirname(__DIR__) . "/plugins/taobaoClient/TopClient.php";
        require_once dirname(__DIR__) . "/plugins/taobaoClient/TbkScPublisherInfoSaveRequest.php";
        $c = new TopClient;
        $c->appkey = $this->union['appKey'];
        $c->secretKey = $this->union['appSecret'];
        $req = new TbkScPublisherInfoSaveRequest;
        $req->setInviterCode($this->union['publisherInviteCode']);
        $req->setInfoType("2");
        $resp = $c->execute($req, $sessionKey);
        $result = \Common\Common::transition_array($resp);
        if(isset($result['code'])){
            return ['status'=>false,'msg'=>isset($result['sub_msg']) ? $result['sub_msg'] : $result['sub_code']];
        }
        return ['status'=>true,'msg'=>'数据获取成功','data'=>$result['data']['special_id']];
    }


    /**
     * 生成邀请
     */
    public function Invitecode($rid,$sessionKey='')
    {
        require_once dirname(__DIR__) . "/plugins/taobaoClient/TopClient.php";
        require_once dirname(__DIR__) . "/plugins/taobaoClient/TbkScInvitecodeGetRequest.php";
        $c            = new TopClient;
        $c->appkey = $this->union['appKey'];
        $c->secretKey = $this->union['appSecret'];
        $req          = new TbkScInvitecodeGetRequest;
        $req->setRelationId($rid);
        $req->setRelationApp("common");
        $req->setCodeType("3");
        $resp = $c->execute($req,'6202a09f09f782ed9ZZ36d048b558e24caedba182b2e77e402914441');
        var_dump($resp);exit;
    }

    //淘宝授权获取access_token
    public function get_auth_token($code,$uuid){
        require_once dirname(__DIR__) . "/plugins/taobaoClient/TopClient.php";
        require_once dirname(__DIR__) . "/plugins/taobaoClient/TopAuthTokenCreateRequest.php";
        $c = new TopClient;
        $c->appkey = $this->union['appKey'];
        $c->secretKey = $this->union['appSecret'];
        $c->gatewayUrl = "https://eco.taobao.com/router/rest";
        $req = new TopAuthTokenCreateRequest;
        $req->setCode($code);
        $req->setUuid($uuid);
        $resp = $c->execute($req);
        return $resp;
    }


    /**
     * 饿了么口碑通用返回数据
     */
    public function elmMaterialTurnList($data,$tb_rid,$tb_sid){
        if(isset($data[0]) && empty($data[0])){
            return [];
        }
        $responseData = [];
        foreach($data as $key=>$value){
            $temData['title'] = isset($value['usable_shop_name']) ? $value['usable_shop_name'] : "";
            $temData['shopLogo'] = isset($value['pict_url']) ? $value['pict_url'] : "";
            $temData['sales'] = isset($value['volume']) ? $value['volume'] : "";
            if($tb_rid && $tb_sid){
                $temData['itemUrl'] = isset($value['item_url']) ? $value['item_url'] : '';
            }else{
                $temData['itemUrl'] = '';
            }
            $temData['daySurplusStock'] = 0;
            $temData['type'] = 1;
            $temData['deliveryPrice'] = 0;
            $temData['bonusCent'] = "0";
            $temData['deliveryFee'] = isset($value['localization_extend']['delivery_fee']) ? $value['localization_extend']['delivery_fee'] : "";
            $temData['deliveryType'] = isset($value['localization_extend']['delivery_type']) ? $value['localization_extend']['delivery_type'] : "";
            $temData['deliveryTime'] = isset($value['localization_extend']['order_lead_time']) ? $value['localization_extend']['order_lead_time'] : "";
            $temData['deliveryDistance'] = isset($value['distance']) ? $value['distance'] : "";
            $temData['serviceRating'] = isset($value['localization_extend']['user_rating']) ? $value['localization_extend']['user_rating'] : "";

            $salesTag = isset($value['localization_extend']['sale_tags']['string']) ? $value['localization_extend']['sale_tags']['string'] : [];
            if($salesTag){
                $salesTag = array_merge(["最高10%"],$salesTag);
            }else{
                $salesTag = ["最高10%"];
            }
            $temData['salesTag'] = $salesTag;
            $temData['shopId'] = isset($value['usable_shop_id']) ? $value['usable_shop_id'] : "";
            $temData['activityId'] = '';
            $temData['bountyMinLimitCent'] = 0;
            $temData['bonusCent'] = 0;
            $temData['recommendTips'] = isset($value['localization_extend']['recommend_reasons']['string'][0]) ? $value['localization_extend']['recommend_reasons']['string'][0] : '';
            $responseData[] = $temData;
        }
        return $responseData;
    }



    /**
     * https://open.taobao.com/api.htm?docId=35896&docType=2
     * 淘宝饿了么相关物料
     */
    public function dgMaterialOptional($params,$tb_rid,$tb_sid,$osType=2){
        $osType = isset($params['osType']) && $params['osType'] ? $params['osType'] : '2';
        require_once dirname(__DIR__) . "/plugins/taobaoClient/TopClient.php";
        require_once dirname(__DIR__) . "/plugins/taobaoClient/TbkDgMaterialOptionalRequest.php";
        $topClient            = new \TopClient();
        $topClient->appkey = $this->union['appKey'];
        $topClient->secretKey = $this->union['appSecret'];
        $req = new \TbkDgMaterialOptionalRequest();
        $req->setPageNo((int)$params['page']);
        $req->setPageSize((int)$params['page_size']);
        $req->setMaterialId($params['cate_id']);
        $req->setLongitude($params['longitude']);
        $req->setLatitude($params['latitude']);
        if(isset($params['keywords']) && !empty($params['keywords'])){
            $req->setQ($params['keywords']);
        }
        if(isset($params['pageResultKey']) && !empty($params['pageResultKey'])){
            $req->setPageResultKey($params['pageResultKey']);
        }
        if($tb_rid && $tb_sid){
            $req->setRelationId($tb_rid);
            $req->setSpecialId($tb_sid);
        }
        $req->setAdzoneId($this->union['androidMm']);
        $resp = $topClient->execute($req);
        $responseMsgData = json_decode(json_encode($resp),true);
        $responseMsgResult = ['status'=>false,'msg'=>'数据获取不成功','data'=>[]];
        if(isset($responseMsgData['result_list']['map_data'])){
            $responseMsgResult['status'] = true;
            $responseMsgResult['msg'] = "获取成功";
            $responseData['data'] = $this->elmMaterialTurnList($responseMsgData['result_list']['map_data'],$tb_rid,$tb_sid);
            $responseData['pageResultKey'] = isset($responseMsgData['page_result_key']) ? $responseMsgData['page_result_key'] : '';
            $responseMsgResult['data'] = $responseData;
        }else{
            $responseMsgResult['msg'] = isset($responseMsgData['sub_msg']) ? $responseMsgData['sub_msg'] : '';
        }
        return $responseMsgResult;
    }


    /**
     * 饿了么口碑通用返回数据
     */
    public function elmStorepromotionTurnList($data){
        $responseData = [];
        foreach($data as $key=>$value){
            $temData['shopId'] = isset($value['shop_id']) ? $value['shop_id'] : "";
            $temData['activityId'] = isset($value['title']) ? $value['title'] : "";
            $temData['title'] = isset($value['title']) ? $value['title'] : "";
            $temData['shopLogo'] = isset($value['shop_logo']) ? $value['shop_logo'] : "";
            $temData['sales'] = isset($value['indistinct_monthly_sales']) ? $value['indistinct_monthly_sales'] : 0;
            $temData['itemUrl'] = '';
            $temData['type'] = 2;
            $temData['deliveryPrice'] = isset($value['delivery_price']) ? $value['delivery_price'] : -1;
            $temData['deliveryFee'] = isset($value['delivery_fee']) ? $value['delivery_fee'] : -1;
            $temData['deliveryType'] = "";
            $temData['daySurplusStock'] = isset($value['activity']['daily_sellable_quantity']) ? $value['activity']['daily_sellable_quantity'] : 0;
            $temData['deliveryTime'] = isset($value['delivery_time']) ? $value['delivery_time'] : "";
            $temData['deliveryDistance'] = isset($value['delivery_distance']) ? $value['delivery_distance'] : "";
            $temData['serviceRating'] = isset($value['service_rating']) ? $value['service_rating'] : "";
            $temData['salesTag'] = [];
            $temData['activityId'] = isset($value['activity']['activity_id']) ? $value['activity']['activity_id'] : '';
            $temData['bountyMinLimitCent'] = isset($value['activity']['bounty_min_limit_cent']) && !empty($value['activity']['bounty_min_limit_cent']) ? $value['activity']['bounty_min_limit_cent'] : 0;
            $temData['bonusCent'] = isset($value['activity']['bonus_cent']) ? $value['activity']['bonus_cent'] : 0;
            $temData['recommendTips'] = isset($value['recommend_reasons']['string'][0]) ? $value['recommend_reasons']['string'][0] : '';
            $responseData[] = $temData;
        }
        return $responseData;
    }


    /**
     * https://open.taobao.com/api.htm?docId=60447&docType=2&scopeId=24408#scopes
     * 本地联盟饿了么单店推广店铺列表
     */
    public function elemePromotionStorepromotionQuery($params){
        require_once dirname(__DIR__) .'/plugins/taobaoClient/TopClient.php';
        require_once dirname(__DIR__) .'/plugins/taobaoClient/AlibabaAlscUnionElemePromotionStorepromotionQueryRequest.php';
        require_once dirname(__DIR__) .'/plugins/taobaoClient/PromotionQueryRequest.php';
        $c = new \TopClient();
        $c->appkey = $this->union['appKey'];
        $c->secretKey = $this->union['appSecret'];
        $req = new \AlibabaAlscUnionElemePromotionStorepromotionQueryRequest();
        $query_request = new \PromotionQueryRequest();
        $query_request->pid=$this->union['androidPid'];
        $query_request->longitude=$params['longitude'];
        $query_request->latitude=$params['latitude'];
        $query_request->sort_type="distance";
        $query_request->in_activity="true";
        $query_request->has_bonus_stock="true";
        $query_request->page_size=$params['pageSize'];
        if(isset($params['pageResultKey']) && !empty($params['pageResultKey'])){
            $query_request->session_id = $params['pageResultKey'];
        }
//        $query_request->sid="1111";
        $query_request->biz_type="activityCps";
        $req->setQueryRequest(json_encode($query_request));
        $resp = $c->execute($req);
        $responseMsgData = json_decode(json_encode($resp),true);
        $responseMsgResult = ['status'=>false,'msg'=>'获取失败'];
        if(isset($responseMsgData['data']['records']['store_promotion_dto'])){
            $responseMsgResult['status'] = true;
            $responseMsgResult['msg'] = "获取成功";
            $responseData['data'] = $this->elmStorepromotionTurnList($responseMsgData['data']['records']['store_promotion_dto']);
            $responseData['pageResultKey'] = $responseMsgData['request_id'];
            $responseMsgResult['data'] = $responseData;
        }else{
            $responseMsgResult['msg'] = isset($responseMsgData['msg']) ? $responseMsgData['msg'] : '获取失败';
        }
        return $responseMsgResult;
    }





    /**
     * @func android 淘宝授权
     * @param $user_id 用户id
     */
    public function taobao_authorizes($user_id)
    {
        $url   = 'https://oauth.taobao.com/authorize';
        $param = [
            'client_id'     => $this->union['appKey'],
            'response_type' => 'code',
            'redirect_uri'  => $this->union['tbCallBack'],
            'view'          => 'wap',
            'state'         => $user_id,
        ];
        return $url = $url . '?' . http_build_query($param);
    }
}
